<template>
  <!-- 应急通讯录 -->
  <div class="emerAddressBook">
    <basic-container>
      <avue-crud :option="option"
                 :table-loading="loading"
                 :data="data"
                 :page.sync="page"
                 :permission="permissionList"
                 :before-open="beforeOpen"
                 v-model="form"
                 ref="crud"
                 @row-update="rowUpdate"
                 @row-save="rowSave"
                 @row-del="rowDel"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectionChange"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
                 @on-load="onLoad">
        <template slot="menuLeft">
          <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.addressbook_delete" @click="handleDelete">删 除</el-button>
          <el-button type="success" size="small" icon="el-icon-upload2" plain v-if="permission.addressbook_import" @click="handleImport">导 入</el-button>
          <el-button type="warning" size="small" icon="el-icon-download" plain v-if="permission.addressbook_export" @click="handleExport">导 出</el-button>
        </template>
      </avue-crud>

      <!-- 导入弹窗-->
      <el-dialog title="应急通讯录导入" append-to-body :visible.sync="excelBox" width="555px">
        <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter">
          <template slot="excelTemplate">
            <el-button type="primary" @click="handleTemplate">
              点击下载<i class="el-icon-download el-icon--right"></i>
            </el-button>
          </template>
        </avue-form>
      </el-dialog>

    </basic-container>
  </div>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/emer/addressbook";
  import {getDeptList} from "@/api/mmhi/major_dangerous_sources";
  import {validateTelephone} from "@/api/mmhi/validate";
  import {getToken} from "@/util/auth";
  import {mapGetters} from "vuex";

  const tenantId = JSON.parse(localStorage.getItem("saber-tenantId")).content;

  export default {
    data() {
      return {
        form: {},
        query: {},
        excelBox: false,
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        excelForm: {},
        excelOption: {
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              label: '模板上传',
              prop: 'excelFile',
              type: 'upload',
              drag: true,
              loadText: '模板上传中，请稍等',
              showFileList: false,
              span: 24,
              propsHttp: {
                res: 'data'
              },
              tip: '请上传 .xls,.xlsx 标准格式文件',
              action: "/api/emerAddressBook/addressbook/import-addressBook"
            },
            {
              label: '模板下载',
              prop: 'excelTemplate',
              formslot: true,
              span: 24
            }
          ]
        },
        option: {
          height:'auto',
          refreshBtn: true,
          columnBtn: true,
          calcHeight: 30,
          dialogWidth: 950,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "企业名称",
              prop: "qymc",
              align: "center",
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "姓名",
              prop: "xm",
              align: "center",
              search: true,
              maxlength:100,
              rules: [{
                required: true,
                message: "请输入姓名",
                trigger: "blur"
              }]
            },
            {
              label: "部门",
              prop: "bm",
              align: "center",
              type:"tree",
              dicData: [],
              props: {
                label: "title"
              },
              checkStrictly: true,
              rules: [{
                required: true,
                message: "请选择部门",
                trigger: "click"
              }]
            },
            {
              label: "职务",
              prop: "zw",
              align: "center",
              type: "select",
              dicUrl: "/api/blade-system/post/select?tenantId=" + tenantId,
              props: {
                label: "postName",
                value: "id",
              },
              rules: [{
                  required: true,
                  message: "请选择职务",
                  trigger: "click"
              }]
            },
            {
              label: "应急电话(手机)",
              prop: "yjdh",
              align: "center",
              maxlength:11,
              rules: [{
                required: true,
                validator: validateTelephone,
                trigger: "blur"
              }]
            },
            {
              label: "固定电话（区号-电话号码）",
              prop: "gddh",
              width:180,
              align: "center",
              maxlength:13,
              rules: [{
                required: true,
                validator: validateTelephone,
                trigger: "blur"
              }]
            },
            {
              label: "备注",
              prop: "bz",
              align: "center",
              type: "textarea",
              maxlength:500,
              span: 24,
              minRows: 6,
              hide: true,
            },
            {
              label: "企业id",
              prop: "bladeDeptId",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "租户id",
              prop: "tenantId",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建人",
              prop: "createUser",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建部门",
              prop: "createDept",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建时间",
              prop: "createTime",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            }
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.addressbook_add, false),
          viewBtn: this.vaildData(this.permission.addressbook_view, false),
          delBtn: this.vaildData(this.permission.addressbook_delete, false),
          editBtn: this.vaildData(this.permission.addressbook_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    mounted() {
      this.initData();
    },
    methods: {
      // 初始化数据
      initData() {
        getDeptList(tenantId).then(res => {
          const column = this.findObject(this.option.column, "bm");
          column.dicData = res.data.data;
        }).then(() => {

        });
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      handleImport() {
        this.excelBox = true;
      },
      uploadAfter(res, done, loading, column) {
        window.console.log(column);
        this.excelBox = false;
        this.refreshChange();
        done();
      },
      handleTemplate() {
        window.open(`/api/emerAddressBook/addressbook/export-template?${this.website.tokenHeader}=${getToken()}`);
      },
      handleExport() {
        this.$confirm("是否导出应急通信录信息?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          window.open(`/api/emerAddressBook/addressbook/export-addressBook?${this.website.tokenHeader}=${getToken()}`);
        });
      }
    }
  };
</script>

<style lang="scss" scpoed>
  .emerAddressBook {
    .avue-crud {
      .avue-crud__search {
        .avue-form__row:nth-child(1) {
          .el-form-item__label {
            text-align: unset;
            width: 90px !important;
          }

          .el-form-item__content {
            margin-left: 90px !important;
          }
        }
      }
    }
  }

</style>
